/**
 * Copyright 2016-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.inmorn.extspring.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.inmorn.extspring.controller.BaseController;
import com.inmorn.extspring.util.StringUtils;

/**
 * 拦截前段对控制器请求
 *  设置请求参数
 * @author Jeff.Li
 *
 */
public class ControllerInterceptor implements HandlerInterceptor{

	/**
	 * 不需要拦截的请求
	 */
	public String[] allowUrls;
	 
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object object, ModelAndView model) throws Exception {
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object object) throws Exception {
		String requestUrl = request.getRequestURI();
		if(StringUtils.isNotEmpty(requestUrl)){
			requestUrl = requestUrl.replace(request.getContextPath(), "");
		}
		
		boolean nextOk = true;
        if(null != allowUrls && allowUrls.length>=1)  
            for(String url : allowUrls)
                if(requestUrl.contains(url))
                	return true;
        
        //提前执行,设置请求参数
        if(object instanceof HandlerMethod){
        	object = ((HandlerMethod)object).getBean();
        }
        if(object instanceof BaseController){
        	BaseController handler = (BaseController) object; 
	        handler.beforeInvoke(request,requestUrl);
        }
		return nextOk;
	}

	public String[] getAllowUrls() {
		return allowUrls;
	}

	public void setAllowUrls(String[] allowUrls) {
		this.allowUrls = allowUrls;
	}
	
}
